<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <!-- 插入到left插槽位置 -->
        <template #left>
          <i class="el-icon-info" />
          <span>本月: 社保在缴 公积金在缴</span>
        </template>
         <!-- 插入到right插槽位置 -->
        <template #right>
          <el-button type="primary" size="small" @click="$router.push('/import')">员工导入</el-button>
          <el-button type="primary" size="small" @click="exportExcel">员工导出</el-button>
          <el-button type="primary" size="small" @click="add">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list">
          <el-table-column label="序号" type="index"/>
          <el-table-column label="姓名" prop="username"/>
          <el-table-column label="头像" width="110">
            <template #default="scope">
              <!-- <img :src="scope.row.staffPhoto" alt="" width="80"> -->
              <el-image :src="scope.row.staffPhoto" class="avatar" @click="createQr(scope.row)">
                <!-- 具名插槽新语法  图片加载出错的时候自动显示 -->
                <template #error>
                  <!-- <i class="el-icon-picture-outline" /> -->
                  <img src="@/assets/common/bigUserHeader.png" width="80">
                </template>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber"/>
          <el-table-column label="聘用形式">
            <template #default="{row}">
              {{formEmployment(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName"/>
          <el-table-column label="入职时间" width="180">
            <template #default="{row}">
              {{ formatDate(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作"  fixed="right" width="200">
            <template #default="{row}">
              <el-button type="text" size="small" @click="goDetail(row.id)">查看</el-button>
              <el-button type="text" size="small" @click="assignRoles(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="fetchDelEmploy(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :total="total"
            :current-page="params.page"
            :page-size="params.size"
            layout="prev, pager, next"
            @current-change="pageChange"
          />
        </div>
      </el-card>
    </div>
    <add-employee :show-visible="showVisible" @close-dialog="closeDialog" @fetch-List="fetchList"></add-employee>
    <el-dialog 
    class="assign-role" 
    title="分配角色" 
    :visible="showRoleDialog"
    @close="roleClose"
    @open="roleOpen"
    >
      <!-- 这里准备复选框 -->
      <el-checkbox-group v-model="checkList">
        <!-- 这里的label用来匹配 如果在checkList中找到 就会被选中 -->
        <!--
          问题：显示的是id 选中的也是id值
          预期：显示的中文 选中的id label依旧绑定id作为提交给后端的字段
          然后通过插槽配合差值表达式渲染显示到页面中的中文
         -->
        <el-checkbox
          v-for="item in roleList"
          :key="item.id"
          :label="item.id"
        >
          {{ item.name }}
        </el-checkbox>
      </el-checkbox-group>
      <template #footer>
        <el-button type="primary" size="small" @click="confirmAssign">确定</el-button>
        <el-button size="small" @click="roleClose">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee, assignRoles } from '@/api/employee'
import AddEmployee from './components/add-employee.vue'
import dayjs from 'dayjs'
import { getExportData } from '@/utils/excel'
import { getUserDetailById } from '@/api/user'
import { getRoleList } from '@/api/setting'
export default {
  name: 'Employees',
  components: {
    AddEmployee
  },
  data() {
    return {
      list: [],
      params: {
        page: 1,
        size: 10
      },
      total: 0,
      showVisible: false,
      showRoleDialog: false,
      curId: '',
      checkList: [], // 选中项的label值
      roleList: [] // 角色列表
    }
  },
  mounted() {
    this.fetchList()
  },
  methods: {
    async fetchList() {
      const { rows, total } = await getEmployeeList(this.params)
      console.log(rows, total)
      this.list = rows
      this.total = total
    },
    formEmployment(type) {
      // 枚举写法,简化了代码
      const map = {
        1: '正式员工',
        2: '非正式员工'
      }
      return map[type]
    },
    formatDate(value) {
    return dayjs(value).format('YYYY-MM-DD')
    },
    // 分页
    pageChange(page) {
      this.params.page = page
      this.fetchList()
    },
    // 删除
    fetchDelEmploy(id) {
       this.$confirm('你确认要删除么?', '温馨提示').then(async() => {
        await delEmployee(id)
        this.fetchList()
        this.$message.success('删除员工成功')
      }).catch(error => {
        console.log(error)
      })
    },
    // 点击关闭弹窗
    closeDialog() {
      this.showVisible = false
    },
    // 打开弹窗
    add() {
      this.showVisible = true
    },
    // 员工导出
    exportExcel() {
      // 按需导入，动态导入
      import('@/vendor/Export2Excel').then(async(excel) => {
        console.log(excel)
        // 调用接口 获取员工信息列表
        const res = await getEmployeeList(this.params)
        // 数据二次处理,后端返回的数据经过处理才能使用
        const headerRelation = {
          '姓名': 'username',
          '手机号': 'mobile',
          '入职日期': 'timeOfEntry',
          '工号': 'workNumber',
          '聘用形式': 'formOfEmployment',
          '部门': 'departmentName'
        }
        const { data } = getExportData(res.rows, headerRelation)
        // 使用excel的方法字符串转换成excel
        excel.export_json_to_excel({
          header: Object.keys(headerRelation), // 表头header 必填 要求是一个数组
          data: data, // 表格数据body 要求是一个二维数组
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    goDetail(id) {
      this.$router.push({
        path: '/detail',
        query: {
          id
        }
      })
    },
    // 分配角色
    assignRoles(id) {
      this.curId =id
      this.showRoleDialog = true
    },
    // 关闭弹窗
    roleClose() {
      this.showRoleDialog = false
      // 清空页面
      this.checkList = []
    },
    // 获取分配详情
    async roleOpen() {
      const res = await getRoleList()
      this.roleList = res.rows
      // 获取一下详情
      const detail = await getUserDetailById(this.curId)
      this.checkList = detail.roleIds
    },
    async confirmAssign() {
      await assignRoles({
        id: this.curId,
        roleIds: this.checkList
      })
      // 弹框关闭
      this.roleClose()
      this.$message.success('分配角色成功')
    }
  }
}
</script>
